import { createRouter, createWebHistory } from 'vue-router'
import { routes, dynamicRoutes } from './routes'
// import { local } from '/@/utils/storage'
import pinia from '/@/stores/index'
import { storeToRefs } from 'pinia'
import { useRoutesList } from '/@/stores/routesList'
import { useThemeConfig } from '/@/stores/themeConfig'
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes'

// 读取 `/src/stores/themeConfig.ts` 是否开启后端控制路由配置
const storesThemeConfig = useThemeConfig(pinia)
const { themeConfig } = storeToRefs(storesThemeConfig)
const { isRequestRoutes } = themeConfig.value

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach(async (to, _, next) => {
    // if (to.path !== '/login') {
    //     if (!local.get('token')) {
    //         return '/login'
    //     }
    // } else {
        const storesRoutesList = useRoutesList(pinia)
        const { routesList } = storeToRefs(storesRoutesList)
        if (routesList.value.length === 0) {
            if (isRequestRoutes) {
                next()
            } else {
                // https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
                // await initFrontEndControlRoutes();
                routesList.value.push(...dynamicRoutes)
                next({ path: to.path, query: to.query });
            }
        } else {
            next()
        }
        const storesTagsView = useTagsViewRoutes(pinia)
        const tagsList = dynamicRoutes.flatMap(route => {
            if (route.children) {
                return route.children.map(child => ({
                    ...child
                }))
            }
            return route
        })
        storesTagsView.setTagsViewRoutes(tagsList)
    // }
    

    // next()
})

export default router